package com.ad.aidai.fragments.look_profile;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.Button;

import com.ad.aidai.bean.ProfileBean;
import com.ad.aidai.bean.UserWithSchool;
import com.ad.aidai.common.RongImManager;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.common.widgets.imageview.CircleImageView;
import com.ad.aidai.network.ADUrl;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResultWithData;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * LookProfilePresenter
 * <p>
 * Created by pure on 2017/1/12.
 */

public class LookProfilePresenter implements LookProfileContract.Presenter {

    private Activity mContext;
    private LookProfileContract.View mView;
    private CompositeSubscription mSubscriptions;
    private LookProfileAdapter mAdapter;
    private List<ProfileBean> datas;

    private long userId;
    private boolean show = false;
    private String userName = "";
    private boolean showButton = false;

    public LookProfilePresenter(Activity context, LookProfileContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        initData();
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
    }

    private void initData() {
        datas = new ArrayList<>();
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_HEAD, "头像", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "昵称", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "性别", ""));
        datas.add(new ProfileBean());
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "学校", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "学号", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "姓名", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "班级", ""));
        datas.add(new ProfileBean());
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "积分", ""));
        datas.add(new ProfileBean());
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "手机", ""));
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "支付宝", ""));
        datas.add(new ProfileBean());
        datas.add(new ProfileBean(ProfileBean.VIEWTYPE_STRING, "个性签名", ""));
    }

    @Override
    public List<ProfileBean> getDatas() {
        return datas;
    }

    @Override
    public void loadUserData() {

        Bundle bundle = mView.getBundle();
        if (bundle == null) {
            mView.toast("加载失败");
            return;
        }
        userId = bundle.getLong("userId");
        show = bundle.getBoolean("show");
        showButton = bundle.getBoolean("showButton");
        if (!show) {
            showButton = false;
        }

        mView.showLoading();
        NetWork.getAccountOperationApi()
                .lookProfile(userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResultWithData<UserWithSchool>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("lookProfile").e(e.getMessage());
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResultWithData<UserWithSchool> lookProfileFromNet) {
                        Logger.t("lookProfile").i(lookProfileFromNet.toString());
                        if (lookProfileFromNet.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            mView.closeLoading(true);
                            RongImManager.refreshUserInfoCache(lookProfileFromNet.getData());
                            loadData(lookProfileFromNet.getData());
                        } else {
                            mView.closeLoading(false);
                        }
                    }
                });

    }

    private void loadData(UserWithSchool user) {

        if(!show) {
            mView.showDialog();
        }

        user.setSchoolName();
        Long schoolId = user.getSchoolId();
        if (schoolId == null) {
            schoolId = 0L;
        }

        String url = ADUrl.HEAD_ICON_URL.replace("{schoolId}", schoolId + "").replace("{photoName}", user.getUserIcon
                ());
        datas.get(0).setValue(url);
        userName = user.getUserName();
        datas.get(1).setValue(userName);
        mView.setTitle(userName);
        if(user.getUserSex() != null) {
            datas.get(2).setValue(user.getUserSex() == 0 ? "男" : "女");
        }

        String schoolName = "";
        if (!CheckUtil.checkStrNull(user.getSchoolName())) {
            schoolName = user.getSchoolName();
        }

        datas.get(4).setValue(schoolName);
        if (!show) {
            user.setUserStuNumber(getHiddenString(user.getUserStuNumber()));
            user.setUserRealName(getHiddenString(user.getUserRealName()));
            user.setUserClass(getHiddenString(user.getUserClass()));
            user.setUserTel(getHiddenString(user.getUserTel()));
            user.setUserPayNum(getHiddenString(user.getUserPayNum()));
        }
        datas.get(5).setValue(user.getUserStuNumber());
        datas.get(6).setValue(user.getUserRealName());
        datas.get(7).setValue(user.getUserClass());
        datas.get(9).setValue(user.getUserCredits()+"");
        datas.get(11).setValue(user.getUserTel());
        String payNum = user.getUserPayNum();
        if(CheckUtil.checkStrNull(payNum)) {
            payNum = "未填写";
        }
        datas.get(12).setValue(payNum);
        String note = user.getUserPersonalNote();
        if(CheckUtil.checkStrNull(note)) {
            note = "太懒了，什么都不写!";
        }
        datas.get(14).setValue(note);
        if (showButton) {
            datas.add(new ProfileBean().setType(ProfileBean.VIEWTYPE_BUTTON).setName("发消息"));
        }

        mAdapter.notifyItemRangeChanged(0, datas.size());
    }

    private String getHiddenString(String str) {
        if (CheckUtil.checkStrNull(str)) {
            return "";
        }
        String result = "";

        for (int i = 0; i < str.length(); ++i) {
            result += "*";
        }

        return result;
    }

    @Override
    public void onItemLongClick(int position) {
        if (show) {
            switch (position) {
                case 1:
                case 2:
                case 4:
                case 5:
                case 6:
                case 7:
                case 9:
                case 11:
                case 12:
                case 14:
                    getDataToCopyWord(position);
                    break;
            }
        } else {
            switch (position) {
                case 1:
                case 2:
                case 4:
                case 9:
                case 14:
                    getDataToCopyWord(position);
                    break;
            }
        }
    }

    private void getDataToCopyWord(int position){
        String content = (String) datas.get(position).getValue();
        if(!CheckUtil.checkStrNull(content)){
            copyWord(content);
        }
    }

    private void copyWord(String content) {
        // 从API11开始android推荐使用android.content.ClipboardManager
        // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
        ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(content);
        mView.toast("已复制到剪切板");
    }

    @Override
    public void onItemSubClick(View view, int position) {
        Logger.t(LookProfilePresenter.class.getSimpleName()).i(position + "---");
        //点击了头像
        if (position == 0 && view instanceof CircleImageView) {
            mView.startDragPhotoActivity((CircleImageView) view, (String) datas.get(0).getValue());
        }
        //点击按钮
        if (position == 15 && view instanceof Button) {
            Logger.t(LookProfilePresenter.class.getSimpleName()).i(position + "---button--" + ((Button) view).getText
                    ().toString());
            if (((Button) view).getText().toString().equals("发消息")) {
                mView.startMessageActivity(String.valueOf(userId), userName);
            }
        }
    }

    @Override
    public void setAdapter() {
        mAdapter = mView.getAdapter();
    }
}
